﻿#include "user_admin.h"
#include <Global_Class.h>
#include <QtableWidget>
#include "AddUser_admin.h"
#include <QMessageBox>
#include "UndoRedo_User.h"
#include <cctype>
#include <stdexcept>
#include <vector>
#include <regex>
#include <QTimer>
void setupTableStyle(QTableWidget* table);//优化UI界面
QTableWidgetItem* createTableItem(const QString& text);
std::string statusList(std::string status)
{
	if (status == "已封禁") {
		return "0"; // 封禁状态
	}
	else if (status == "正常") {
		return "1"; // 正常状态
	}
	return "1"; // 默认返回正常状态
};

user_admin::user_admin(QWidget* parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	SetupAUToolBar(); // Setup the toolbar for user admin
	refershAUtable(allData->usersQueue); // Refresh the user table when the admin indow is created
}

user_admin::~user_admin()
{
}
//未优化UI界面版本
//void user_admin::refershAUtable(std::deque<users> usersQueue)
//{
//	std::string status[2] = { "已封禁", "正常" };
//	QTableWidget* table = ui.tableWidget;
//	table->setRowCount(static_cast<int>(usersQueue.size()));
//	table->setColumnCount(8);
//	table->setHorizontalHeaderLabels({
//		QString::fromUtf8("序号"),
//		QString::fromUtf8("用户名"),
//		QString::fromUtf8("昵称"),
//		QString::fromUtf8("密码"),
//		QString::fromUtf8("手机号"),
//		QString::fromUtf8("权限"),
//		QString::fromUtf8("证件号码"),
//		QString::fromUtf8("账号状态")
//		});
//	for (size_t i = 0; i < usersQueue.size(); ++i) {
//		users& user = usersQueue[i];
//		table->setItem(static_cast<int>(i), 0, new QTableWidgetItem(QString::fromStdString(user.getUserId())));
//		table->setItem(static_cast<int>(i), 1, new QTableWidgetItem(QString::fromStdString(user.getUsername())));
//		table->setItem(static_cast<int>(i), 2, new QTableWidgetItem(QString::fromStdString(user.getDisplayName())));
//		table->setItem(static_cast<int>(i), 3, new QTableWidgetItem(QString::fromStdString(user.getPassword())));
//		table->setItem(static_cast<int>(i), 4, new QTableWidgetItem(QString::fromStdString(user.getPhone())));
//		table->setItem(static_cast<int>(i), 5, new QTableWidgetItem(QString::fromStdString(user.getRole())));
//		table->setItem(static_cast<int>(i), 6, new QTableWidgetItem(QString::fromStdString(user.getIdCard())));
//		int state = std::stoi(user.getState());
//		table->setItem(static_cast<int>(i), 7, new QTableWidgetItem(QString::fromStdString(status[state])));
//	}
//
//
//	    // 调整列宽自适应内容
//    table->resizeColumnsToContents();
//}

//优化UI界面版本
void user_admin::refershAUtable(std::deque<users> usersQueue)
{
	std::string status[2] = { "已封禁", "正常" };
	QTableWidget* table = ui.tableWidget;

	// 基本设置
	table->setRowCount(static_cast<int>(usersQueue.size()));
	table->setColumnCount(8);
	table->setHorizontalHeaderLabels({
		QString::fromUtf8("序号"),
		QString::fromUtf8("用户名"),
		QString::fromUtf8("昵称"),
		QString::fromUtf8("密码"),
		QString::fromUtf8("手机号"),
		QString::fromUtf8("权限"),
		QString::fromUtf8("证件号码"),
		QString::fromUtf8("账号状态")
		});

	// 应用样式
	setupTableStyle(table);

	// 填充数据
	for (size_t i = 0; i < usersQueue.size(); ++i) {
		users& user = usersQueue[i];

		table->setItem(static_cast<int>(i), 0, createTableItem(QString::number(i + 1)));
		table->setItem(static_cast<int>(i), 1, createTableItem(QString::fromStdString(user.getUsername())));
		table->setItem(static_cast<int>(i), 2, createTableItem(QString::fromStdString(user.getDisplayName())));

		// 密码保密显示
		QString password = QString::fromStdString(user.getPassword());
		table->setItem(static_cast<int>(i), 3, createTableItem(password));

		table->setItem(static_cast<int>(i), 4, createTableItem(QString::fromStdString(user.getPhone())));
		table->setItem(static_cast<int>(i), 5, createTableItem(QString::fromStdString(user.getRole())));
		table->setItem(static_cast<int>(i), 6, createTableItem(QString::fromStdString(user.getIdCard())));

		// 状态列
		int state = std::stoi(user.getState());
		QTableWidgetItem* statusItem = createTableItem(QString::fromStdString(status[state]));
		if (state == 0) {
			statusItem->setForeground(QBrush(QColor("#f44336")));
		}
		else {
			statusItem->setForeground(QBrush(QColor("#4caf50")));
		}
		table->setItem(static_cast<int>(i), 7, statusItem);
	}
}

// 辅助函数
void setupTableStyle(QTableWidget * table) {
	// 设置表格样式
	table->setStyleSheet(R"(
        QTableWidget {
            background-color: white;
            alternate-background-color: #f8f9fa;
            gridline-color: #dee2e6;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            outline: none;
			color: black;
			font-family: "SimSun", "宋体"; 
        }
        QTableWidget::item {
            padding: 10px 8px;
            border-bottom: 1px solid #dee2e6;
            font-size: 13px;
        }
        QTableWidget::item:selected {
            background-color: #e3f2fd;
            color: #1565c0;
        }
        QTableWidget::item:hover {
            background-color: #f5f5f5;
        }
    )");

	// 表头样式
	table->horizontalHeader()->setStyleSheet(R"(
        QHeaderView::section {
            background-color: #2196f3;
            color: white;
            font-weight: bold;
            padding: 12px 8px;
            border: none;
            border-right: 1px solid #1e88e5;
            font-size: 14px;
        }
        QHeaderView::section:last {
            border-right: none;
        }
        QHeaderView::section:pressed {
            background-color: #1976d2;
        }
    )");

	// 表格行为
	table->setSelectionBehavior(QAbstractItemView::SelectRows);
	table->setSelectionMode(QAbstractItemView::SingleSelection);
	table->setAlternatingRowColors(true);
	table->setEditTriggers(QAbstractItemView::NoEditTriggers);
	table->setSortingEnabled(true);
	table->verticalHeader()->setVisible(false);

	// 列宽设置
	table->horizontalHeader()->setStretchLastSection(true);
	table->setColumnWidth(0, 60);
	table->setColumnWidth(1, 120);
	table->setColumnWidth(2, 120);
	table->setColumnWidth(3, 100);
	table->setColumnWidth(4, 120);
	table->setColumnWidth(5, 80);
	table->setColumnWidth(6, 150);

	// 设置行高
	for (int i = 0; i < table->rowCount(); ++i) {
		table->setRowHeight(i, 40);
	}
}

QTableWidgetItem* createTableItem(const QString & text) {
	QTableWidgetItem* item = new QTableWidgetItem(text);
	item->setTextAlignment(Qt::AlignCenter);
	return item;
}



void user_admin::SetupAUToolBar()
{
	QTableWidget* table = ui.tableWidget;
	QAction* addToolAction = new QAction(QIcon(""), "添加", this);
	QAction* deleteToolAction = new QAction(QIcon(""), "删除", this);
	QAction* viewToolAction = new QAction(QIcon(""), "查看", this);
	QAction* modifyToolAction = new QAction(QIcon(""), "修改", this);
	QAction* redoToolAction = new QAction(QIcon(""), "恢复", this);
	QAction* undoToolAction = new QAction(QIcon(""), "撤销", this);
	QAction* refreshpassword = new QAction(QIcon(""), "重置密码", this);
	
	ui.menubar->addAction(addToolAction);
	ui.menubar->addAction(deleteToolAction);
	ui.menubar->addAction(viewToolAction);
	ui.menubar->addAction(modifyToolAction);
	ui.menubar->addAction(redoToolAction);
	ui.menubar->addAction(undoToolAction);
	ui.menubar->addAction(refreshpassword);
	connect(addToolAction, &QAction::triggered, this, &user_admin::AddUser);
	connect(deleteToolAction, &QAction::triggered, this, &user_admin::DeleteUser);
	connect(viewToolAction, &QAction::triggered, this, &user_admin::ViewUser);
	connect(modifyToolAction, &QAction::triggered, this, &user_admin::ModifyUser);
	connect(refreshpassword, &QAction::triggered, this, &user_admin::RefreshPassword);

	connect(redoToolAction, &QAction::triggered, [&]() {
		if (undoRedo.redoAction()) {
			refershAUtable(allData->usersQueue); // 刷新用户表格
		} else {
			QMessageBox::warning(this, "重做失败", "没有可重做的操作。");
		}
		});
	connect(undoToolAction, &QAction::triggered, [&]() {
		if (undoRedo.undoAction()) {
			refershAUtable(allData->usersQueue); // 刷新用户表格
		} else {
			QMessageBox::warning(this, "撤销失败", "没有可撤销的操作。");
		}
		});
	connect(ui.Search_Button, &QPushButton::clicked, this, [this]
		{
			SearchUser(); // 搜索用户
		});
	//双击账号状态单元格，自动弹出是否封禁用户账号，或解封用户账号的对话框
	connect(table, &QTableWidget::cellDoubleClicked, this, [this](int row, int column) {
		if (column == 7) { // 账号状态列
			QTableWidget* table = ui.tableWidget;
			QString userId = table->item(row, 0)->text();
			QString currentState = table->item(row, column)->text();
			QString newState = (currentState == "正常") ? "已封禁" : "正常";
			if (QMessageBox::question(this, "确认修改", QString("是否将用户 %1 的状态修改为 %2？").arg(userId).arg(newState)) == QMessageBox::Yes) {
				allData->usersQueue[row].setState(statusList(newState.toStdString()));
				refershAUtable(allData->usersQueue); // 刷新用户表格
			}
		}
		});
}

void user_admin::AddUser()
{
	//打开添加用户窗口
	AddUser_admin dlg(this);
	while(dlg.exec() == QDialog::Accepted)
	{
		if(!dlg.passwordsMatch()) {
			QMessageBox::warning(this, "密码错误", "两次输入的密码不一致，请检查。");
			continue;
		}
		
		users newUser = dlg.User();
		std::regex phoneRegex("^1[3-9]\\d{9}$");
		if (!std::regex_match(newUser.getPhone(), phoneRegex)) {
			QMessageBox::warning(this, "修改失败", "手机号格式不正确！");
			continue;
		}

		std::regex idCardRegex("^\\d{17}[\\dXx]$");
		if (!std::regex_match(newUser.getIdCard(), idCardRegex)) {
			QMessageBox::warning(this, "修改失败", "身份证号格式不正确！");
			continue;
		}
		newUser.setState("1");
		allData->usersQueue.push_back(newUser); // 添加新用户到全局数据
		int newIdx = allData->usersQueue.size() + 1;
		undoRedo.recordOp(Operation::makeSingle(Add, newUser, newIdx));
		refershAUtable(allData->usersQueue); // 刷新用户表格
		break;
	}
}

//void user_admin::DeleteUser()
//{
//	QTableWidget* table = ui.tableWidget;
//
//	/* ① 收集被选中的行号 */
//	QSet<int> rowSet;
//	for (QTableWidgetItem* item : table->selectedItems())
//		rowSet.insert(item->row());
//
//	if (rowSet.isEmpty()) {
//		QMessageBox::information(this, "提示", "请先选择要删除的行");
//		return;
//	}
//	/* ② 统一确认 */
//	const int count = rowSet.size();
//	if (QMessageBox::question(
//		this,
//		"确认删除",
//		tr("确定要删除选中的 %1 条记录吗？").arg(count),
//		QMessageBox::Yes | QMessageBox::No,
//		QMessageBox::No) != QMessageBox::Yes)
//		return;
//
//
//
//	/* ③ 行号降序，防止 row 失效 */
//	QList<int> rows = rowSet.values();
//	std::sort(rows.begin(), rows.end(), std::greater<int>());
//	//
//	Operation op;
//	op.type = Delete;
//
//	for (int row : rows) {
//		const QString id = table->item(row, 0)->text();
//		auto it = std::find_if(allData->usersQueue.begin(), allData->usersQueue.end(),
//			[&](users& u) { return u.getUserId() == id.toStdString(); });
//		if (it != allData->usersQueue.end()) {
//			op.Users.push_back(*it);
//			op.indices.push_back(row);   // 原位置
//		}
//	}
//	undoRedo.recordOp(op);               // ★ 先记录，再执行下面的删除循环
//
//	/* ④ 同步删除数据 + UI */
//	for (int row : rows) {
//		const QString id = table->item(row, 0)->text();
//
//		/* 4-1 删容器 */
//		auto it = std::find_if(allData->usersQueue.begin(),
//			allData->usersQueue.end(),
//			[&](users& u) {
//				return (u.getUserId() == id.toStdString()) ? 1 : 0;
//			});
//		if (it != allData->usersQueue.end())
//			allData->usersQueue.erase(it);
//
//		/* 4-2 删 UI 行 */
//		table->removeRow(row);
//	}
//}

//以下为优化UI界面版本---------------------------------------------------------------------
void user_admin::DeleteUser()
{
	QTableWidget* table = ui.tableWidget;

	/* ① 收集被选中的行号 */
	QSet<int> rowSet;
	for (QTableWidgetItem* item : table->selectedItems())
		rowSet.insert(item->row());

	if (rowSet.isEmpty()) {
		// 优化提示框样式
		QMessageBox msgBox(this);
		msgBox.setWindowTitle("提示");
		msgBox.setText("请先选择要删除的用户");
		msgBox.setIcon(QMessageBox::Information);
		msgBox.setStyleSheet(
			"QMessageBox {"
			"    background-color: #f8f9fa;"
			"    font-family: 'Microsoft YaHei';"
			"    font-size: 10pt;"
			"}"
			"QMessageBox QLabel {"
			"    color: #2c3e50;"
			"    padding: 10px;"
			"}"
			"QMessageBox QPushButton {"
			"    background-color: #3498db;"
			"    color: white;"
			"    border: none;"
			"    border-radius: 4px;"
			"    padding: 8px 16px;"
			"    font-weight: bold;"
			"    min-width: 80px;"
			"}"
			"QMessageBox QPushButton:hover {"
			"    background-color: #2980b9;"
			"}"
		);
		msgBox.addButton("确定", QMessageBox::AcceptRole);
		msgBox.exec();
		return;
	}

	/* ② 优化确认对话框 */
	const int count = rowSet.size();

	// 创建自定义确认对话框
	QDialog confirmDialog(this);
	confirmDialog.setWindowTitle("确认删除");
	confirmDialog.setFixedSize(400, 200);
	confirmDialog.setStyleSheet(
		"QDialog {"
		"    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
		"                              stop: 0 #f8f9fa, stop: 1 #e9ecef);"
		"    border-radius: 8px;"
		"    font-family: 'Microsoft YaHei';"
		"}"
	);

	QVBoxLayout* layout = new QVBoxLayout(&confirmDialog);

	// 警告图标和文字
	QHBoxLayout* headerLayout = new QHBoxLayout();
	QLabel* iconLabel = new QLabel("⚠️");
	iconLabel->setStyleSheet("font-size: 24pt; color: #e74c3c;");
	QLabel* titleLabel = new QLabel("确认删除");
	titleLabel->setStyleSheet(
		"QLabel {"
		"    color: #2c3e50;"
		"    font-size: 14pt;"
		"    font-weight: bold;"
		"}"
	);
	headerLayout->addWidget(iconLabel);
	headerLayout->addWidget(titleLabel);
	headerLayout->addStretch();

	// 消息内容
	QLabel* messageLabel = new QLabel(
		tr("确定要删除选中的 <b>%1</b> 个用户吗？<br><br>"
			"<span style='color: #7f8c8d; font-size: 9pt;'>"
			"谨慎操作！操作错误及时用撤销按钮撤回。</span>").arg(count)
	);
	messageLabel->setStyleSheet(
		"QLabel {"
		"    color: #34495e;"
		"    font-size: 10pt;"
		"    padding: 10px;"
		"    background-color: rgba(255,255,255,0.7);"
		"    border-radius: 6px;"
		"}"
	);
	messageLabel->setWordWrap(true);

	// 显示选中的用户信息（可选）
	QLabel* selectedUsersLabel = new QLabel();
	selectedUsersLabel->setStyleSheet(
		"QLabel {"
		"    color: #7f8c8d;"
		"    font-size: 9pt;"
		"    background-color: rgba(255,255,255,0.5);"
		"    border-radius: 4px;"
		"    padding: 5px;"
		"}"
	);

	QStringList selectedUsers;
	QList<int> rows = rowSet.values();
	std::sort(rows.begin(), rows.end());
	for (int i = 0; i < qMin(3, rows.size()); ++i) { // 最多显示3个用户
		int row = rows[i];
		QString userName = table->item(row, 1)->text(); // 假设第1列是用户名
		selectedUsers << userName;
	}

	if (rows.size() > 3) {
		selectedUsersLabel->setText("选中的用户: " + selectedUsers.join(", ") + tr(" 等 %1 个用户").arg(count));
	}
	else {
		selectedUsersLabel->setText("选中的用户: " + selectedUsers.join(", "));
	}

	// 按钮布局
	QHBoxLayout* buttonLayout = new QHBoxLayout();
	QPushButton* cancelButton = new QPushButton("❌ 取消");
	QPushButton* confirmButton = new QPushButton("🗑️ 确认删除");

	// 设置按钮样式
	QString buttonStyle = R"(
        QPushButton {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-weight: bold;
            font-size: 10pt;
            min-width: 100px;
        }
    )";

	cancelButton->setStyleSheet(buttonStyle +
		"QPushButton {"
		"    background-color: #95a5a6;"
		"    color: white;"
		"}"
		"QPushButton:hover {"
		"    background-color: #7f8c8d;"
		"}"
	);

	confirmButton->setStyleSheet(buttonStyle +
		"QPushButton {"
		"    background-color: #e74c3c;"
		"    color: white;"
		"}"
		"QPushButton:hover {"
		"    background-color: #c0392b;"
		"}"
	);

	cancelButton->setCursor(Qt::PointingHandCursor);
	confirmButton->setCursor(Qt::PointingHandCursor);

	buttonLayout->addStretch();
	buttonLayout->addWidget(cancelButton);
	buttonLayout->addWidget(confirmButton);

	// 组装布局
	layout->addLayout(headerLayout);
	layout->addWidget(messageLabel);
	layout->addWidget(selectedUsersLabel);
	layout->addStretch();
	layout->addLayout(buttonLayout);

	// 连接按钮信号
	connect(cancelButton, &QPushButton::clicked, &confirmDialog, &QDialog::reject);
	connect(confirmButton, &QPushButton::clicked, &confirmDialog, &QDialog::accept);

	// 显示对话框并等待用户选择
	if (confirmDialog.exec() != QDialog::Accepted) {
		return;
	}

	/* ③ 行号降序，防止 row 失效 */
	std::sort(rows.begin(), rows.end(), std::greater<int>());

	Operation op;
	op.type = Delete;

	for (int row : rows) {
		const QString id = table->item(row, 0)->text();
		auto it = std::find_if(allData->usersQueue.begin(), allData->usersQueue.end(),
			[&](users& u) { return u.getUserId() == id.toStdString(); });
		if (it != allData->usersQueue.end()) {
			op.Users.push_back(*it);
			op.indices.push_back(row);   // 原位置
		}
	}
	undoRedo.recordOp(op);               // ★ 先记录，再执行下面的删除循环

	/* ④ 同步删除数据 + UI */
	for (int row : rows) {
		const QString id = table->item(row, 0)->text();

		/* 4-1 删容器 */
		auto it = std::find_if(allData->usersQueue.begin(),
			allData->usersQueue.end(),
			[&](users& u) {
				return (u.getUserId() == id.toStdString()) ? 1 : 0;
			});
		if (it != allData->usersQueue.end())
			allData->usersQueue.erase(it);

		/* 4-2 删 UI 行 */
		table->removeRow(row);
	}

	// 显示删除成功提示
	showDeleteSuccessMessage(count);
}

void user_admin::showDeleteSuccessMessage(int count)
{
	// 创建浮动提示消息
	QMessageBox* successMsg = new QMessageBox(this);
	successMsg->setWindowTitle("操作成功");
	successMsg->setText(tr("成功删除 %1 个用户").arg(count));
	successMsg->setIcon(QMessageBox::Information);
	successMsg->setStyleSheet(
		"QMessageBox {"
		"    background-color: #d4edda;"
		"    border: 1px solid #c3e6cb;"
		"    border-radius: 8px;"
		"    font-family: 'Microsoft YaHei';"
		"}"
		"QMessageBox QLabel {"
		"    color: #155724;"
		"    padding: 15px;"
		"    font-size: 10pt;"
		"}"
		"QMessageBox QPushButton {"
		"    background-color: #28a745;"
		"    color: white;"
		"    border: none;"
		"    border-radius: 4px;"
		"    padding: 8px 16px;"
		"    font-weight: bold;"
		"    min-width: 80px;"
		"}"
		"QMessageBox QPushButton:hover {"
		"    background-color: #218838;"
		"}"
	);

	// 自动关闭提示
	QTimer::singleShot(2000, successMsg, &QMessageBox::accept);
	successMsg->exec();

	// 可选：刷新表格显示
	// refreshTable();
}

//------------------------------------------------------------------------

//void user_admin::ViewUser()
//{
//	// 查看用户的逻辑
//	QTableWidget* table = ui.tableWidget;
//	int currentRow = table->currentRow();
//	if (currentRow < 0) {
//		QMessageBox::warning(this, "查看失败", "请先选择要查看的用户。");
//		return;
//	}
//	
//	// 获取用户信息并显示
//	users& user = allData->usersQueue[currentRow];
//	QString userInfo = QString("用户名: %1\n昵称: %2\n手机号: %3\n权限: %4\n证件号码: %5")
//		.arg(QString::fromStdString(user.getUsername()))
//		.arg(QString::fromStdString(user.getDisplayName()))
//		.arg(QString::fromStdString(user.getPhone()))
//		.arg(QString::fromStdString(user.getRole()))
//		.arg(QString::fromStdString(user.getIdCard()));
//	QMessageBox::information(this, "用户信息", userInfo);
// 
// 
//}


void user_admin::ViewUser()
{
	QTableWidget* table = ui.tableWidget;
	int currentRow = table->currentRow();

	if (currentRow < 0) {
		// 优化警告提示框
		QMessageBox warningBox(this);
		warningBox.setWindowTitle("查看失败");
		warningBox.setText("请先选择要查看的用户");
		warningBox.setIcon(QMessageBox::Warning);
		warningBox.setStyleSheet(
			"QMessageBox {"
			"    background-color: #fff3cd;"
			"    border: 1px solid #ffeaa7;"
			"    border-radius: 8px;"
			"    font-family: 'Microsoft YaHei';"
			"}"
			"QMessageBox QLabel {"
			"    color: #856404;"
			"    padding: 15px;"
			"    font-size: 10pt;"
			"}"
			"QMessageBox QPushButton {"
			"    background-color: #ffc107;"
			"    color: #212529;"
			"    border: none;"
			"    border-radius: 4px;"
			"    padding: 8px 16px;"
			"    font-weight: bold;"
			"    min-width: 80px;"
			"}"
			"QMessageBox QPushButton:hover {"
			"    background-color: #e0a800;"
			"}"
		);
		warningBox.exec();
		return;
	}

	// 获取用户信息
	users& user = allData->usersQueue[currentRow];

	// 创建自定义详情对话框
	QDialog detailDialog(this);
	detailDialog.setWindowTitle("用户详细信息");
	detailDialog.setFixedSize(450, 500);
	detailDialog.setStyleSheet(
		"QDialog {"
		"    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
		"                              stop: 0 #f8f9fa, stop: 1 #e9ecef);"
		"    border-radius: 10px;"
		"    font-family: 'Microsoft YaHei';"
		"}"
	);

	QVBoxLayout* mainLayout = new QVBoxLayout(&detailDialog);

	// 头部 - 标题和用户图标
	QHBoxLayout* headerLayout = new QHBoxLayout();
	QLabel* iconLabel = new QLabel("👤");
	iconLabel->setStyleSheet(
		"QLabel {"
		"    font-size: 28pt;"
		"    padding: 10px;"
		"}"
	);

	QLabel* titleLabel = new QLabel("用户详细信息");
	titleLabel->setStyleSheet(
		"QLabel {"
		"    color: #2c3e50;"
		"    font-size: 16pt;"
		"    font-weight: bold;"
		"    padding: 10px;"
		"}"
	);

	headerLayout->addWidget(iconLabel);
	headerLayout->addWidget(titleLabel);
	headerLayout->addStretch();

	// 用户信息卡片
	QWidget* infoCard = new QWidget();
	infoCard->setStyleSheet(
		"QWidget {"
		"    background-color: white;"
		"    border-radius: 8px;"
		"    border: 1px solid #e0e0e0;"
		"}"
	);

	QVBoxLayout* cardLayout = new QVBoxLayout(infoCard);
	cardLayout->setSpacing(12);
	cardLayout->setContentsMargins(20, 20, 20, 20);

	// 创建信息项函数
	auto createInfoItem = [](const QString& label, const QString& value, const QString& icon = "") {
		QHBoxLayout* itemLayout = new QHBoxLayout();

		QLabel* iconLabel = new QLabel(icon);
		iconLabel->setStyleSheet(
			"QLabel {"
			"    font-size: 12pt;"
			"    color: #7f8c8d;"
			"    min-width: 20px;"
			"}"
		);

		QLabel* nameLabel = new QLabel(label + ":");
		nameLabel->setStyleSheet(
			"QLabel {"
			"    color: #34495e;"
			"    font-weight: bold;"
			"    font-size: 10pt;"
			"    min-width: 80px;"
			"}"
		);

		QLabel* valueLabel = new QLabel(value);
		valueLabel->setStyleSheet(
			"QLabel {"
			"    color: #2c3e50;"
			"    font-size: 10pt;"
			"    background-color: #f8f9fa;"
			"    border-radius: 4px;"
			"    padding: 8px 12px;"
			"    border: 1px solid #e9ecef;"
			"}"
		);
		valueLabel->setWordWrap(true);

		itemLayout->addWidget(iconLabel);
		itemLayout->addWidget(nameLabel);
		itemLayout->addWidget(valueLabel);
		itemLayout->setStretchFactor(valueLabel, 1);

		return itemLayout;
		};

	// 添加用户信息项
	cardLayout->addLayout(createInfoItem("用户ID", QString::fromStdString(user.getUserId()), "🆔"));
	cardLayout->addLayout(createInfoItem("用户名", QString::fromStdString(user.getUsername()), "👤"));
	cardLayout->addLayout(createInfoItem("显示名称", QString::fromStdString(user.getDisplayName()), "📛"));
	cardLayout->addLayout(createInfoItem("手机号", QString::fromStdString(user.getPhone()), "📱"));

	// 权限显示带颜色编码
	QString role = QString::fromStdString(user.getRole());
	QString roleColor = (role == "admin") ? "#e74c3c" : "#27ae60";
	QString roleText = QString("<span style='color: %1; font-weight: bold;'>%2</span>")
		.arg(roleColor).arg(role);

	QHBoxLayout* roleLayout = new QHBoxLayout();
	QLabel* roleIcon = new QLabel("🔐");
	roleIcon->setStyleSheet("QLabel { font-size: 12pt; color: #7f8c8d; min-width: 20px; }");

	QLabel* roleNameLabel = new QLabel("权限:");
	roleNameLabel->setStyleSheet("QLabel { color: #34495e; font-weight: bold; font-size: 10pt; min-width: 80px; }");

	QLabel* roleValueLabel = new QLabel();
	roleValueLabel->setText(roleText);
	roleValueLabel->setStyleSheet(
		"QLabel {"
		"    font-size: 10pt;"
		"    background-color: #f8f9fa;"
		"    border-radius: 4px;"
		"    padding: 8px 12px;"
		"    border: 1px solid #e9ecef;"
		"}"
	);

	roleLayout->addWidget(roleIcon);
	roleLayout->addWidget(roleNameLabel);
	roleLayout->addWidget(roleValueLabel);
	roleLayout->setStretchFactor(roleValueLabel, 1);
	cardLayout->addLayout(roleLayout);

	cardLayout->addLayout(createInfoItem("身份证号", QString::fromStdString(user.getIdCard()), "🆔"));

	// 状态信息
	QString state = QString::fromStdString(user.getState());
	QString stateText = (state == "1") ? "✅ 正常" : "❌ 禁用";
	QString stateColor = (state == "1") ? "#27ae60" : "#e74c3c";

	QHBoxLayout* stateLayout = new QHBoxLayout();
	QLabel* stateIcon = new QLabel((state == "1") ? "✅" : "❌");
	stateIcon->setStyleSheet("QLabel { font-size: 12pt; min-width: 20px; }");

	QLabel* stateNameLabel = new QLabel("状态:");
	stateNameLabel->setStyleSheet("QLabel { color: #34495e; font-weight: bold; font-size: 10pt; min-width: 80px; }");

	QLabel* stateValueLabel = new QLabel();
	stateValueLabel->setText(QString("<span style='color: %1; font-weight: bold;'>%2</span>")
		.arg(stateColor).arg(stateText));
	stateValueLabel->setStyleSheet(
		"QLabel {"
		"    font-size: 10pt;"
		"    background-color: #f8f9fa;"
		"    border-radius: 4px;"
		"    padding: 8px 12px;"
		"    border: 1px solid #e9ecef;"
		"}"
	);

	stateLayout->addWidget(stateIcon);
	stateLayout->addWidget(stateNameLabel);
	stateLayout->addWidget(stateValueLabel);
	stateLayout->setStretchFactor(stateValueLabel, 1);
	cardLayout->addLayout(stateLayout);

	// 底部按钮
	QHBoxLayout* buttonLayout = new QHBoxLayout();
	QPushButton* closeButton = new QPushButton("关闭");
	QPushButton* editButton = new QPushButton("编辑用户");

	closeButton->setStyleSheet(
		"QPushButton {"
		"    background-color: #95a5a6;"
		"    color: white;"
		"    border: none;"
		"    border-radius: 6px;"
		"    padding: 10px 20px;"
		"    font-weight: bold;"
		"    font-size: 10pt;"
		"    min-width: 100px;"
		"}"
		"QPushButton:hover {"
		"    background-color: #7f8c8d;"
		"}"
	);

	editButton->setStyleSheet(
		"QPushButton {"
		"    background-color: #3498db;"
		"    color: white;"
		"    border: none;"
		"    border-radius: 6px;"
		"    padding: 10px 20px;"
		"    font-weight: bold;"
		"    font-size: 10pt;"
		"    min-width: 100px;"
		"}"
		"QPushButton:hover {"
		"    background-color: #2980b9;"
		"}"
	);

	closeButton->setCursor(Qt::PointingHandCursor);
	editButton->setCursor(Qt::PointingHandCursor);

	buttonLayout->addStretch();
	buttonLayout->addWidget(editButton);
	buttonLayout->addWidget(closeButton);

	// 组装主布局
	mainLayout->addLayout(headerLayout);
	mainLayout->addWidget(infoCard);
	mainLayout->addStretch();
	mainLayout->addLayout(buttonLayout);

	// 连接按钮信号
	connect(closeButton, &QPushButton::clicked, &detailDialog, &QDialog::accept);
	connect(editButton, &QPushButton::clicked, [&]() {
		// 这里可以添加编辑用户的逻辑
		QMessageBox::information(this, "提示", "编辑用户功能待实现");
		});

	// 显示对话框
	detailDialog.exec();
}


//void user_admin::ModifyUser()
//{
//	QTableWidget* table = ui.tableWidget;
//	int currentRow = table->currentRow();
//
//	// 检查是否选择了有效行
//	if (currentRow < 0) {
//		QMessageBox::warning(this, "修改失败", "请先选择要修改的用户。");
//		return;
//	}
//
//	// 获取当前选中的用户
//	users& currentUser = allData->usersQueue[currentRow];
//
//	// 打开修改对话框并填充当前用户信息
//	AddUser_admin dlg(this);
//	dlg.setWindowTitle("修改用户信息");
//	if (currentUser.getUsername() == "系统管理员") {
//		dlg.ui->name_lineEdit->setReadOnly(true); // 用户名不可修改
//		dlg.ui->power_comboBox->setEnabled(false); // 权限不可修改
//	}
//	// 设置对话框中的初始值
//	dlg.setUsername(QString::fromStdString(currentUser.getUsername()));
//	dlg.setDisplayName(QString::fromStdString(currentUser.getDisplayName()));
//	dlg.setPhone(QString::fromStdString(currentUser.getPhone()));
//	dlg.setRole(QString::fromStdString(currentUser.getRole()));
//	dlg.setIdCard(QString::fromStdString(currentUser.getIdCard()));
//
//	//// 密码字段留空，用户需要重新输入
//	//dlg.setPassword("");
//	//dlg.setConfirmPassword("");
//
//	//密码字段为空且无法修改
//	dlg.EmptyWords();
//
//
//	if (dlg.exec() == QDialog::Accepted) {
//		// 检查密码是否一致
//		if (!dlg.passwordsMatch()) {
//			QMessageBox::warning(this, "密码错误", "两次输入的密码不一致，请检查。");
//			return;
//		}
//		users edited = dlg.User();
//		users old = currentUser;          // 复制旧对象
//
//		// —— 记录 —— 
//		Operation op;
//		op.type = Modify;
//		op.Users = { old, edited };  // 0 = 旧, 1 = 新
//		op.indices = { currentRow };
//		undoRedo.recordOp(op);
//
//		// 更新用户信息
//		users modifiedUser = dlg.User();
//
//		// 保留原始用户名（因为对话框可能不允许修改用户名）
//		modifiedUser.setUserId(currentUser.getUserId());
//		modifiedUser.setUsername(currentUser.getUsername());
//
//		// 如果密码未修改，保留原密码
//		if (modifiedUser.getPassword().empty()) {
//			modifiedUser.setPassword(currentUser.getPassword());
//		}
//
//		// 更新全局数据中的用户信息
//		allData->usersQueue[currentRow] = modifiedUser;
//
//		// 刷新表格
//		refershAUtable(allData->usersQueue);
//
//		QMessageBox::information(this, "成功", "用户信息已更新。");
//	}
//}


void user_admin::ModifyUser()
{
	QTableWidget* table = ui.tableWidget;
	int currentRow = table->currentRow();

	if (currentRow < 0) {
		// 优化警告提示框
		QMessageBox warningBox(this);
		warningBox.setWindowTitle("修改失败");
		warningBox.setText("请先选择要修改的用户");
		warningBox.setIcon(QMessageBox::Warning);
		warningBox.setStyleSheet(
			"QMessageBox {"
			"    background-color: #fff3cd;"
			"    border: 1px solid #ffeaa7;"
			"    border-radius: 8px;"
			"    font-family: 'Microsoft YaHei';"
			"}"
			"QMessageBox QLabel {"
			"    color: #856404;"
			"    padding: 15px;"
			"    font-size: 10pt;"
			"}"
			"QMessageBox QPushButton {"
			"    background-color: #ffc107;"
			"    color: #212529;"
			"    border: none;"
			"    border-radius: 4px;"
			"    padding: 8px 16px;"
			"    font-weight: bold;"
			"    min-width: 80px;"
			"}"
			"QMessageBox QPushButton:hover {"
			"    background-color: #e0a800;"
			"}"
		);
		warningBox.exec();
		return;
	}

	// 获取用户信息
	users& user = allData->usersQueue[currentRow];

	// 创建修改用户对话框
	QDialog modifyDialog(this);
	modifyDialog.setWindowTitle("修改用户信息");
	modifyDialog.setFixedSize(500, 650);
	modifyDialog.setStyleSheet(
		"QDialog {"
		"    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
		"                              stop: 0 #f8f9fa, stop: 1 #e9ecef);"
		"    border-radius: 10px;"
		"    font-family: 'Microsoft YaHei';"
		"}"
	);

	QVBoxLayout* mainLayout = new QVBoxLayout(&modifyDialog);

	// 头部 - 标题和编辑图标
	QHBoxLayout* headerLayout = new QHBoxLayout();
	QLabel* iconLabel = new QLabel("✏️");
	iconLabel->setStyleSheet(
		"QLabel {"
		"    font-size: 28pt;"
		"    padding: 10px;"
		"}"
	);

	QLabel* titleLabel = new QLabel("修改用户信息");
	titleLabel->setStyleSheet(
		"QLabel {"
		"    color: #2c3e50;"
		"    font-size: 16pt;"
		"    font-weight: bold;"
		"    padding: 10px;"
		"}"
	);

	headerLayout->addWidget(iconLabel);
	headerLayout->addWidget(titleLabel);
	headerLayout->addStretch();

	// 表单容器
	QWidget* formCard = new QWidget();
	formCard->setStyleSheet(
		"QWidget {"
		"    background-color: white;"
		"    border-radius: 8px;"
		"    border: 1px solid #e0e0e0;"
		"}"
	);

	QGridLayout* formLayout = new QGridLayout(formCard);
	formLayout->setVerticalSpacing(15);
	formLayout->setHorizontalSpacing(20);
	formLayout->setContentsMargins(25, 25, 25, 25);

	// 样式定义
	QString labelStyle = R"(
        QLabel {
            color: #34495e;
            font-weight: bold;
            font-size: 10pt;
            padding: 5px 0px;
        }
    )";

	QString lineEditStyle = R"(
        QLineEdit {
            padding: 10px 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            background-color: white;
            color: #2c3e50;
            font-size: 10pt;
            selection-background-color: #3498db;
        }
        QLineEdit:focus {
            border-color: #3498db;
            background-color: #fafcff;
        }
        QLineEdit::placeholder {
            color: #a0a0a0;
        }
        QLineEdit:read-only {
            background-color: #f8f9fa;
            color: #7f8c8d;
        }
    )";

	QString comboBoxStyle = R"(
        QComboBox {
            padding: 10px 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            background-color: white;
            color: #2c3e50;
            font-size: 10pt;
            selection-background-color: #3498db;
        }
        QComboBox:focus {
            border-color: #3498db;
        }
        QComboBox::drop-down {
            border: none;
            width: 30px;
        }
        QComboBox::down-arrow {
            image: none;
            border-left: 5px solid transparent;
            border-right: 5px solid transparent;
            border-top: 5px solid #7f8c8d;
        }
        QComboBox:disabled {
            background-color: #f8f9fa;
            color: #7f8c8d;
        }
    )";

	// 创建表单字段
	// 用户ID（不可编辑）
	QLabel* idLabel = new QLabel("🆔 用户ID:");
	idLabel->setStyleSheet(labelStyle);
	QLineEdit* idEdit = new QLineEdit(QString::fromStdString(user.getUserId()));
	idEdit->setStyleSheet(lineEditStyle);
	idEdit->setReadOnly(true);

	// 用户名
	QLabel* usernameLabel = new QLabel("👤 用户名:");
	usernameLabel->setStyleSheet(labelStyle);
	QLineEdit* usernameEdit = new QLineEdit(QString::fromStdString(user.getUsername()));
	usernameEdit->setStyleSheet(lineEditStyle);
	usernameEdit->setPlaceholderText("请输入用户名");

	// 显示名称
	QLabel* displayNameLabel = new QLabel("📛 显示名称:");
	displayNameLabel->setStyleSheet(labelStyle);
	QLineEdit* displayNameEdit = new QLineEdit(QString::fromStdString(user.getDisplayName()));
	displayNameEdit->setStyleSheet(lineEditStyle);
	displayNameEdit->setPlaceholderText("请输入显示名称");

	// 手机号
	QLabel* phoneLabel = new QLabel("📱 手机号:");
	phoneLabel->setStyleSheet(labelStyle);
	QLineEdit* phoneEdit = new QLineEdit(QString::fromStdString(user.getPhone()));
	phoneEdit->setStyleSheet(lineEditStyle);
	phoneEdit->setPlaceholderText("请输入手机号码");

	// 权限
	QLabel* roleLabel = new QLabel("🔐 权限:");
	roleLabel->setStyleSheet(labelStyle);
	QComboBox* roleCombo = new QComboBox();
	roleCombo->setStyleSheet(comboBoxStyle);
	roleCombo->addItems({ "customer", "admin" });
	roleCombo->setCurrentText(QString::fromStdString(user.getRole()));

	// 身份证号
	QLabel* idCardLabel = new QLabel("🆔 身份证号:");
	idCardLabel->setStyleSheet(labelStyle);
	QLineEdit* idCardEdit = new QLineEdit(QString::fromStdString(user.getIdCard()));
	idCardEdit->setStyleSheet(lineEditStyle);
	idCardEdit->setPlaceholderText("请输入身份证号");

	// 状态
	QLabel* stateLabel = new QLabel("📊 状态:");
	stateLabel->setStyleSheet(labelStyle);
	QComboBox* stateCombo = new QComboBox();
	stateCombo->setStyleSheet(comboBoxStyle);
	stateCombo->addItems({ "正常", "禁用" });
	stateCombo->setCurrentText((user.getState() == "1") ? "正常" : "禁用");

	// 密码（可选修改）
	QLabel* passwordLabel = new QLabel("🔒 新密码:");
	passwordLabel->setStyleSheet(labelStyle);
	QLineEdit* passwordEdit = new QLineEdit();
	passwordEdit->setStyleSheet(lineEditStyle);
	passwordEdit->setPlaceholderText("留空表示不修改密码");
	passwordEdit->setEchoMode(QLineEdit::Password);

	// 确认密码
	QLabel* confirmPasswordLabel = new QLabel("🔒 确认密码:");
	confirmPasswordLabel->setStyleSheet(labelStyle);
	QLineEdit* confirmPasswordEdit = new QLineEdit();
	confirmPasswordEdit->setStyleSheet(lineEditStyle);
	confirmPasswordEdit->setPlaceholderText("请再次输入新密码");
	confirmPasswordEdit->setEchoMode(QLineEdit::Password);

	// 密码显示/隐藏功能
	auto setupPasswordToggle = [lineEditStyle](QLineEdit* passwordEdit) {
		QPushButton* toggleBtn = new QPushButton("👁️");
		toggleBtn->setFixedSize(30, 30);
		toggleBtn->setStyleSheet(
			"QPushButton {"
			"    background-color: transparent;"
			"    border: none;"
			"    color: #7f8c8d;"
			"    font-size: 12pt;"
			"}"
			"QPushButton:hover {"
			"    color: #3498db;"
			"}"
		);
		toggleBtn->setCursor(Qt::PointingHandCursor);

		QHBoxLayout* layout = new QHBoxLayout();
		layout->addWidget(passwordEdit);
		layout->addWidget(toggleBtn);
		layout->setContentsMargins(0, 0, 0, 0);
		layout->setSpacing(0);

		QWidget* container = new QWidget();
		container->setLayout(layout);

		connect(toggleBtn, &QPushButton::clicked, [passwordEdit]() {
			static bool visible = false;
			visible = !visible;
			passwordEdit->setEchoMode(visible ? QLineEdit::Normal : QLineEdit::Password);
			});

		return container;
		};

	QWidget* passwordContainer = setupPasswordToggle(passwordEdit);
	QWidget* confirmPasswordContainer = setupPasswordToggle(confirmPasswordEdit);

	// 系统管理员特殊处理
	if (user.getUsername() == "系统管理员") {
		usernameEdit->setReadOnly(true);
		roleCombo->setEnabled(false);

		// 添加提示标签
		QLabel* adminNote = new QLabel("💡 系统管理员的部分信息受到保护");
		adminNote->setStyleSheet(
			"QLabel {"
			"    color: #e74c3c;"
			"    font-size: 9pt;"
			"    font-weight: bold;"
			"    background-color: #ffebee;"
			"    border-radius: 4px;"
			"    padding: 8px;"
			"    border: 1px solid #e74c3c;"
			"}"
		);
		formLayout->addWidget(adminNote, 0, 0, 1, 2);
	}

	// 添加表单字段到布局
	int rowOffset = (user.getUsername() == "系统管理员") ? 1 : 0;

	formLayout->addWidget(idLabel, rowOffset + 0, 0);
	formLayout->addWidget(idEdit, rowOffset + 0, 1);
	formLayout->addWidget(usernameLabel, rowOffset + 1, 0);
	formLayout->addWidget(usernameEdit, rowOffset + 1, 1);
	formLayout->addWidget(displayNameLabel, rowOffset + 2, 0);
	formLayout->addWidget(displayNameEdit, rowOffset + 2, 1);
	formLayout->addWidget(phoneLabel, rowOffset + 3, 0);
	formLayout->addWidget(phoneEdit, rowOffset + 3, 1);
	formLayout->addWidget(roleLabel, rowOffset + 4, 0);
	formLayout->addWidget(roleCombo, rowOffset + 4, 1);
	formLayout->addWidget(idCardLabel, rowOffset + 5, 0);
	formLayout->addWidget(idCardEdit, rowOffset + 5, 1);
	formLayout->addWidget(stateLabel, rowOffset + 6, 0);
	formLayout->addWidget(stateCombo, rowOffset + 6, 1);
	formLayout->addWidget(passwordLabel, rowOffset + 7, 0);
	formLayout->addWidget(passwordContainer, rowOffset + 7, 1);
	formLayout->addWidget(confirmPasswordLabel, rowOffset + 8, 0);
	formLayout->addWidget(confirmPasswordContainer, rowOffset + 8, 1);

	// 底部按钮
	QHBoxLayout* buttonLayout = new QHBoxLayout();
	QPushButton* cancelButton = new QPushButton("❌ 取消");
	QPushButton* saveButton = new QPushButton("💾 保存修改");
	QPushButton* resetButton = new QPushButton("🔄 重置");

	QString buttonStyle = R"(
        QPushButton {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-weight: bold;
            font-size: 10pt;
            min-width: 100px;
        }
    )";

	cancelButton->setStyleSheet(buttonStyle +
		"QPushButton {"
		"    background-color: #95a5a6;"
		"    color: white;"
		"}"
		"QPushButton:hover {"
		"    background-color: #7f8c8d;"
		"}"
	);

	saveButton->setStyleSheet(buttonStyle +
		"QPushButton {"
		"    background-color: #27ae60;"
		"    color: white;"
		"}"
		"QPushButton:hover {"
		"    background-color: #219653;"
		"}"
	);

	resetButton->setStyleSheet(buttonStyle +
		"QPushButton {"
		"    background-color: #3498db;"
		"    color: white;"
		"}"
		"QPushButton:hover {"
		"    background-color: #2980b9;"
		"}"
	);

	cancelButton->setCursor(Qt::PointingHandCursor);
	saveButton->setCursor(Qt::PointingHandCursor);
	resetButton->setCursor(Qt::PointingHandCursor);

	buttonLayout->addWidget(resetButton);
	buttonLayout->addStretch();
	buttonLayout->addWidget(cancelButton);
	buttonLayout->addWidget(saveButton);

	// 组装主布局
	mainLayout->addLayout(headerLayout);
	mainLayout->addWidget(formCard);
	mainLayout->addStretch();
	mainLayout->addLayout(buttonLayout);

	// 密码验证函数
	auto validatePassword = [passwordEdit, confirmPasswordEdit, lineEditStyle]() {
		QString password = passwordEdit->text();
		QString confirm = confirmPasswordEdit->text();

		if (!confirm.isEmpty() && password != confirm) {
			confirmPasswordEdit->setStyleSheet(
				"QLineEdit {"
				"    padding: 10px 12px;"
				"    border: 2px solid #e74c3c;"
				"    border-radius: 6px;"
				"    background-color: #ffebee;"
				"    color: #2c3e50;"
				"    font-size: 10pt;"
				"}"
			);
			return false;
		}
		else {
			confirmPasswordEdit->setStyleSheet(lineEditStyle);
			return true;
		}
		};

	// 连接信号
	connect(passwordEdit, &QLineEdit::textChanged, validatePassword);
	connect(confirmPasswordEdit, &QLineEdit::textChanged, validatePassword);

	// 重置按钮功能
	connect(resetButton, &QPushButton::clicked, [&]() {
		usernameEdit->setText(QString::fromStdString(user.getUsername()));
		displayNameEdit->setText(QString::fromStdString(user.getDisplayName()));
		phoneEdit->setText(QString::fromStdString(user.getPhone()));
		roleCombo->setCurrentText(QString::fromStdString(user.getRole()));
		idCardEdit->setText(QString::fromStdString(user.getIdCard()));
		stateCombo->setCurrentText((user.getState() == "1") ? "正常" : "禁用");
		passwordEdit->clear();
		confirmPasswordEdit->clear();
		});

	// 连接按钮信号
	connect(cancelButton, &QPushButton::clicked, &modifyDialog, &QDialog::reject);
	connect(saveButton, &QPushButton::clicked, [&]() {
		// 验证输入
		if (usernameEdit->text().isEmpty()) {
			showErrorMessage("输入错误", "用户名不能为空");
			usernameEdit->setFocus();
			return;
		}

		if (displayNameEdit->text().isEmpty()) {
			showErrorMessage("输入错误", "显示名称不能为空");
			displayNameEdit->setFocus();
			return;
		}

		if (!validatePassword()) {
			showErrorMessage("输入错误", "两次输入的密码不一致");
			confirmPasswordEdit->setFocus();
			return;
		}

		// 更新用户信息
		users modifiedUser = user; // 复制原用户

		modifiedUser.setUsername(usernameEdit->text().toStdString());
		modifiedUser.setDisplayName(displayNameEdit->text().toStdString());
		modifiedUser.setPhone(phoneEdit->text().toStdString());
		modifiedUser.setRole(roleCombo->currentText().toStdString());
		modifiedUser.setIdCard(idCardEdit->text().toStdString());
		modifiedUser.setState((stateCombo->currentText() == "正常") ? "1" : "0");

		// 如果设置了新密码，更新密码
		if (!passwordEdit->text().isEmpty()) {
			modifiedUser.setPassword(passwordEdit->text().toStdString());
		}

		// 记录操作
		Operation op;
		op.type = Modify;
		op.Users = { user, modifiedUser };  // 0 = 旧, 1 = 新
		op.indices = { currentRow };
		undoRedo.recordOp(op);

		// 更新全局数据
		allData->usersQueue[currentRow] = modifiedUser;

		// 刷新表格
		refershAUtable(allData->usersQueue);

		// 显示成功消息
		showSuccessMessage("修改成功", "用户信息已成功更新");

		modifyDialog.accept();
		});

	// 显示对话框
	modifyDialog.exec();
}

void user_admin::showErrorMessage(const QString& title, const QString& message)
{
	QMessageBox errorBox(this);
	errorBox.setWindowTitle(title);
	errorBox.setText(message);
	errorBox.setIcon(QMessageBox::Critical);
	errorBox.setStyleSheet(
		"QMessageBox {"
		"    background-color: #f8d7da;"
		"    border: 1px solid #f5c6cb;"
		"    border-radius: 8px;"
		"    font-family: 'Microsoft YaHei';"
		"}"
		"QMessageBox QLabel {"
		"    color: #721c24;"
		"    padding: 15px;"
		"    font-size: 10pt;"
		"}"
		"QMessageBox QPushButton {"
		"    background-color: #dc3545;"
		"    color: white;"
		"    border: none;"
		"    border-radius: 4px;"
		"    padding: 8px 16px;"
		"    font-weight: bold;"
		"    min-width: 80px;"
		"}"
		"QMessageBox QPushButton:hover {"
		"    background-color: #c82333;"
		"}"
	);
	errorBox.exec();
}

void user_admin::showSuccessMessage(const QString& title, const QString& message)
{
	QMessageBox successBox(this);
	successBox.setWindowTitle(title);
	successBox.setText(message);
	successBox.setIcon(QMessageBox::Information);
	successBox.setStyleSheet(
		"QMessageBox {"
		"    background-color: #d4edda;"
		"    border: 1px solid #c3e6cb;"
		"    border-radius: 8px;"
		"    font-family: 'Microsoft YaHei';"
		"}"
		"QMessageBox QLabel {"
		"    color: #155724;"
		"    padding: 15px;"
		"    font-size: 10pt;"
		"}"
		"QMessageBox QPushButton {"
		"    background-color: #28a745;"
		"    color: white;"
		"    border: none;"
		"    border-radius: 4px;"
		"    padding: 8px 16px;"
		"    font-weight: bold;"
		"    min-width: 80px;"
		"}"
		"QMessageBox QPushButton:hover {"
		"    background-color: #218838;"
		"}"
	);
	successBox.exec();
}

void user_admin::updateTableRow(QTableWidget* table, int row, const users& user)
{
	// 更新表格行显示
	table->item(row, 0)->setText(QString::fromStdString(user.getUserId()));
	table->item(row, 1)->setText(QString::fromStdString(user.getUsername()));
	table->item(row, 2)->setText(QString::fromStdString(user.getDisplayName()));
	table->item(row, 3)->setText(QString::fromStdString(user.getPhone()));
	table->item(row, 4)->setText(QString::fromStdString(user.getRole()));
	table->item(row, 5)->setText(QString::fromStdString(user.getIdCard()));

	// 状态列特殊显示
	QString stateText = (user.getState() == "1") ? "正常" : "禁用";
	QString stateColor = (user.getState() == "1") ? "#27ae60" : "#e74c3c";

	QTableWidgetItem* stateItem = table->item(row, 6);
	if (!stateItem) {
		stateItem = new QTableWidgetItem(stateText);
		table->setItem(row, 6, stateItem);
	}
	else {
		stateItem->setText(stateText);
	}
	stateItem->setForeground(QColor(stateColor));
	stateItem->setFont(QFont("Microsoft YaHei", 9, QFont::Bold));
}


void user_admin::SearchUser() 
{
	std::deque<users> result;
	const QString kw = ui.LE_SearchText->text().trimmed();
	if (kw.isEmpty()) {                      // 关键字为空 ⇒ 显示全部
		refershAUtable(allData->usersQueue);
		return;
	}

	const Qt::CaseSensitivity cs = Qt::CaseInsensitive;

	auto toQ = [](const std::string& s) { return QString::fromStdString(s); };

	for (users& u : allData->usersQueue)
	{
		if (
			u.getDisplayName().find(kw.toStdString()) != std::string::npos ||
			u.getUsername().find(kw.toStdString()) != std::string::npos ||
			u.getPhone().find(kw.toStdString()) != std::string::npos ||
			u.getRole().find(kw.toStdString()) != std::string::npos ||
			u.getIdCard().find(kw.toStdString()) != std::string::npos
			)
		{
			result.push_back(u);
		}
	}
	refershAUtable(result);
}

void user_admin::RefreshPassword()
{
	QTableWidget* table = ui.tableWidget;
	int currentRow = table->currentRow();
	if (currentRow < 0) {
		QMessageBox::warning(this, "重置失败", "请先选择要重置密码的用户。");
		return;
	}
	// 获取当前选中的用户
	users& currentUser = allData->usersQueue[currentRow];
	
	// 生成新密码
	std::string newPassword = "123456"; // 默认密码
	users old = currentUser;          // 复制旧对象
	// —— 记录 —— 
	Operation op;
	op.type = Modify;
	users modifiedUser = currentUser; // 创建一个副本来修改密码
	modifiedUser.setPassword(newPassword);
	op.Users = { old, modifiedUser };  // 0 = 旧, 1 = 新
	op.indices = { currentRow };
	undoRedo.recordOp(op);
	// 更新密码
	currentUser.setPassword(newPassword);
	refershAUtable(allData->usersQueue); // 刷新用户表格
	QMessageBox::information(this, "成功", QString("用户 %1 的密码已重置为: %2")
		.arg(QString::fromStdString(currentUser.getUsername()))
		.arg(QString::fromStdString(newPassword)));
}